﻿using System;
using System.IO;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
namespace Moonlite.ExtensionApi
{
    public sealed class BinarySettingsService : ISettingsService
    {
        private string path;
        private SettingsItemCollection items = new SettingsItemCollection();
        public SettingsItemCollection Items
        {
            get { return items; }
        }
        public string Path
        {
            get { return path; }
            set { path = value; }
        }
        public void Write()
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }
            DirectoryHelper.CreatePath(path);
            Stream stream = null;
            try
            {
                IFormatter formatter = new BinaryFormatter();
                stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
                formatter.Serialize(stream, items);
            }
            catch { }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
        public void Read()
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }
            if (!File.Exists(path))
            {
                throw new IOException("Settings file does not exist.");
            }
            Stream stream = null;
            try
            {
                IFormatter formatter = new BinaryFormatter();
                stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
                items = (SettingsItemCollection)formatter.Deserialize(stream);
            }
            catch { }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
        public BinarySettingsService() { }
        public BinarySettingsService(string path)
        {
            this.path = path;
        }
    }
}
